<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入考试名称" v-model="searchParam.SEARCH_LIKE_exam_name" clearable style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus"
                 @click="handleCreate"> 新增
      </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
              style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true"
               :src=" scope.row[column.prop].indexOf('https://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
               width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                     :inactive-value="0" disabled/>
          <!-- 行内显示tag标签 -->
          <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
          <!--默认显示文本-->
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
          <p>
          <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleUpdate(scope.row)"> 编辑
          </el-button>
          <el-button type="text" icon="el-icon-delete" class="el-button--danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
          </p>
          <p>
          <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleLot(scope.row)">
            考试场次
          </el-button>
          <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleDiscount(scope.row)">生成折扣链接</el-button>
          </p>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="75%" top="5vh" :visible.sync="dialogFormVisible"
               :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 90%">

        <el-form-item v-if="dialogFormVisible" label="证书类型" prop="certId"  >
          <el-select v-model="dataForm.certId" placeholder="请选择证书类型" clearable @change="$forceUpdate()">
            <el-option v-for="item in this.certList" :key="item.id" :label="item.certName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="考试类型" prop="examType">-->
<!--          <el-select v-model="dataForm.examType" placeholder="请选择考试类型">-->
<!--            <el-option :value="1" label="正式"></el-option>-->
<!--            <el-option :value="2" label="练习"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
          <el-form-item label="答题方式" prop="answerType">
              <el-select v-model="dataForm.answerType" placeholder="请选择答题方式">
                  <el-option :value="0" label="笔试"></el-option>
                  <el-option :value="1" label="上机"></el-option>
              </el-select>
          </el-form-item>

        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="dataForm.examName" type="text" show-word-limit  maxlength="32" auto-complete="off" placeholder="请输入考试名称"/>
        </el-form-item>
        <el-form-item label="考试图片(PC)" prop="examImg">
          <cm-upload v-model="dataForm.examImg"></cm-upload>
          <p style="color: red">270px * 155px</P>
        </el-form-item>
        <el-form-item label="考试图片(Mobile)" prop="examImgMobile">
          <cm-upload v-model="dataForm.examImgMobile"></cm-upload>
          <p style="color: red">270px * 155px</P>
        </el-form-item>
        <el-form-item label="考试科目" prop="examSubject">
          <el-select v-model="dataForm.examSubject" placeholder="请选择考试科目">
            <el-option v-for="item in subjectList" :key="item.id" :label="item.levelName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通过分数" prop="passScore">
          <el-input-number v-model="dataForm.passScore" :min="1" :max="1000" label="通过分数"></el-input-number>
        </el-form-item>
        <el-form-item label="允许作答次数" prop="examCount">
          <el-input-number v-model="dataForm.examCount" :min="1" :max="1000" label="允许作答次数"></el-input-number>
        </el-form-item>
<!--        <el-form-item label="允许模拟次数" prop="examCountPractice">-->
<!--          <el-input-number v-model="dataForm.examCountPractice" :min="1" :max="1000" label="允许作答次数"></el-input-number>-->
<!--        </el-form-item>-->
        <el-form-item label="排序" prop="orderNo">
          <el-input-number v-model="dataForm.orderNo" :min="1" label="排序"></el-input-number>
        </el-form-item>
<!--        <el-form-item label="考试状态" prop="examStatus">-->
<!--          <el-select v-model="dataForm.examStatus" placeholder="请选择考试状态">-->
<!--            &lt;!&ndash;            报名 1未开始 2报名中 3已结束 考试 4未开始 5考试中 6已结束&ndash;&gt;-->
<!--            <el-option label="报名未开始" :value="1"></el-option>-->
<!--            <el-option label="报名进行中" :value="2"></el-option>-->
<!--            <el-option label="报名已结束" :value="3"></el-option>-->
<!--            <el-option label="考试未开始" :value="4"></el-option>-->
<!--            <el-option label="考试进行中" :value="5"></el-option>-->
<!--            <el-option label="考试已结束" :value="6"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="考试时长（分钟）" prop="examDuration">
          <el-input-number v-model="dataForm.examDuration" :min="1" :max="1000"
                           label="考试时长（分钟）"></el-input-number>
        </el-form-item>
        <el-form-item label="考试形式" prop="examForm">
          <el-select v-model="dataForm.examForm" placeholder="请选择考试形式">
            <el-option label="线下" :value="0"></el-option>
            <el-option label="线上" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试简介" prop="examIntro">
          <el-input type="textarea" v-model="dataForm.examIntro"></el-input>
        </el-form-item>
        <el-form-item label="考试详情介绍" prop="examDesc">
          <tinymce :height="300" v-model="dataForm.examDesc" id='tinymce' :value="dataForm.examDesc"
                   v-if="dialogFormVisible"></tinymce>
        </el-form-item>
        <el-form-item label="报名开始时间" prop="signStartTime">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.signStartTime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="报名截止时间" prop="signEndTime">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.signEndTime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="考试开始时间" prop="examStartTime">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.examStartTime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="考试结束时间" prop="examEndTime">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.examEndTime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="适合群体" prop="suitGroup">
          <el-input v-model="dataForm.suitGroup" auto-complete="off" placeholder="请输入适合群体"/>
        </el-form-item>
        <el-form-item label="是否免费" prop="ifFree">
          <el-switch v-model="dataForm.ifFree" :active-value="1"
                     :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item v-if="dataForm.ifFree === 0" label="售价" prop="salePrice">
          <el-input-number v-model="dataForm.salePrice" :min="0.01"  label="售价"></el-input-number>
        </el-form-item>
        <el-form-item v-if="dataForm.ifFree === 0" label="原价" prop="originPrice">
          <el-input-number v-model="dataForm.originPrice" :min="0.01"  label="原价"></el-input-number>
        </el-form-item>
        <el-form-item label="正式卷抽题策略" prop="examStrategy">
          <el-select v-model="dataForm.examStrategy" placeholder="请选择抽题策略">
            <el-option v-for="item in strategyList" :label="item.strategyName" :value="item.id"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="练习开关" prop="ifPractice">
          <el-switch v-model="dataForm.ifPractice" :active-value="1" :active-text="'开'" :inactive-value="0" :inactive-text="'关'" ></el-switch>
        </el-form-item>
        <el-form-item label="练习卷抽题策略" prop="practiceExamStrategy" v-if="dataForm.ifPractice===1" >
          <el-select v-model="dataForm.practiceExamStrategy" placeholder="请选择模拟考试试题">
            <el-option v-for="item in strategyList" :label="item.strategyName" :value="item.id"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
<!--      <exam-lot v-if="dataForm.id" :id="dataForm.id"></exam-lot>-->
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="考试场次" width="75%"
        top="5vh"
        :visible.sync="examLogDialog"
        :close-on-click-modal="false"
    >
      <exam-lot v-if="examLogDialog" :id="pid" :examStartTime="examStartTime" :examEndTime="examEndTime" ></exam-lot>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="examLogDialog=false">取消</el-button>
<!--        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>-->
      </div>
    </el-dialog>


    <el-dialog
        title="折扣链接"
        top="5vh"
        :visible.sync="showDiscount"
        :close-on-click-modal="false"
    >
      <Discount v-if="showDiscount" :pid="pid" :discount-type="1"></Discount>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="showDiscount=false">取消</el-button>
        <!--        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>-->
      </div>
    </el-dialog>


  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import CmUpload from '@/components/CmUpload' // 上传图片组件引入
import Tinymce from '@/components/CmUEditor' // 富文本编辑器引入
import ExamLot from '@/views/exam/examLot.vue'
import Discount from './examDiscount.vue'
import Dis from "@/views/exam/examDiscount.vue";

export default {
  name: 'exam',
  components: {
    Dis,
    Pagination,
    CmUpload,
    Tinymce,
    ExamLot,
    Discount,
  },
  directives: {},
  filters: {},
  data() {
    return {
      tableKey: 0,
      tableList: [],//表格数据源
      subjectList: [],
      certList: [],
      strategyList: [],
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: {pageNum: 1, pageSize: 10,},
      searchParam: {},
      examName:'',
      dialogFormVisible: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      examLogDialog: false,//保存表单时loading框
      showDiscount: false,//保存表单时loading框
      columns: [
        {prop: 'examName', label: '考试名称', sortable: false},
        {prop: 'examImg', label: '考试图片', sortable: false, imgFlag: true, width: 140},
        // {
        //   prop: 'difficult', label: '题目难度', sortable: false, tagFlag: true,
        //   tagFormatter: [
        //     {text: '⭐️', value: 1, type: 'success'},
        //     {text: '⭐️⭐️', value: 2, type: 'success'},
        //     {text: '⭐️⭐️⭐️', value: 3, type: 'success'},
        //     {text: '⭐️⭐️⭐️⭐️', value: 4, type: 'success'},
        //     {text: '⭐️⭐️⭐️⭐️⭐️', value: 5, type: 'success'},
        //   ]
        // },
        {prop: 'ifFree', label: '是否免费', sortable: false, switchFlag: true,},
        {prop: 'passScore', label: '通过分数', sortable: false},
        {prop: 'totalScore', label: '试卷总分', sortable: false},
        {prop: 'questionCount', label: '题目数量', sortable: false},
        {
          prop: 'examStatus', label: '考试状态', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '未开始', value: 1, type: 'info'},
            {text: '进行中', value: 2, type: 'success'},
            {text: '已结束', value: 3, type: 'warn'}
          ]
        },
        {
          prop: 'signStatus', label: '报名状态', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '未开始', value: 1, type: 'info'},
            {text: '进行中', value: 2, type: 'success'},
            {text: '已结束', value: 3, type: 'warn'}
          ]
        },
        {
          prop: 'examForm', label: '考试形式', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '线下', value: 0, type: 'success'},
            {text: '线上', value: 1, type: 'success'},
          ]
        },
        {prop: 'createTime', label: '创建时间', sortable: false, width: 140},
        {prop: 'orderNo', label: '排序', sortable: false, width: 50},
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {
        // certId: [{required: true, message: '请先关联证书', trigger: 'change'}],
        // examType: [{required: true, message: '请选择考试类型', trigger: 'change'}],
        examName: [{required: true, message: '请输入考试名称', trigger: 'change'}],
        examImg: [{required: true, message: '请上传考试图片', trigger: 'change'}],
        examSubject: [{required: true, message: '请选择试卷科目', trigger: 'change'}],
        passScore: [{required: true, message: '请设置通过分数', trigger: 'change'}],
        examCount: [{required: true, message: '请设置允许作答次数', trigger: 'change'}],
        examDuration: [{required: true, message: '请设置考试形式', trigger: 'change'}],
        examForm: [{required: true, message: '请设置考试时长', trigger: 'change'}],
        signStartTime: [{required: true, message: '请设置报名开始时间', trigger: 'change'}],
        signEndTime: [{required: true, message: '请设置报名截止时间', trigger: 'change'}],
        examStartTime: [{required: true, message: '请设置考试开始时间', trigger: 'change'}],
        examEndTime: [{required: true, message: '请设置考试截止时间', trigger: 'change'}],
        suitGroup: [{required: true, message: '请选择适合群体', trigger: 'change'}],
        ifFree: [{required: true, message: '请选择是否免费', trigger: 'change'}],
        examStrategy: [{required: true, message: '请设置抽题策略', trigger: 'change'}],
        practiceExamStrategy: [{required: true, message: '请选择模拟考试试题', trigger: 'change'}],
        answerType: [{required: true, message: '请选择答题方式', trigger: 'change'}],
      },
      pid:'',
      examStartTime:'',
      examEndTime:'',
    }
  },
  created() {
    this.getSubjectList();
    this.getStrategyList();
    this.getCertList();
    this.getList();
  },
  methods: {
    getCertList() {
      //【API请求】----获取表格列表数据
      this.$api.getZCertificateList({
        searchParam:{SEARCH_EQ_cert_source :1},
        orderParam: {
          order_no: true
        },
      }).then(response => {
        this.certList = response.data.content
      }).catch((res) => {
      })
    },



    async getCertRelation(id) {
      //【API请求】----获取表格列表数据
      this.$api.getCert({id: id}).then(response => {
        this.dataForm.certId = response.data.certId
        // this.dataForm.certId = Object.assign({}, response.data.certId)
        this.dialogFormVisible = true
        //显示编辑菜单
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.editLoading = false;
        })
      }).catch((res) => {
        this.$message({message: '证书获取失败', type: 'error'})
        this.dialogFormVisible = true
        //显示编辑菜单
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.editLoading = false;
        })
      })
    },
    //获取表格数据
    getList() {
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.pageRequest.orderParam = { create_time:false }
      this.$api.getSExamList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },
    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.getCertRelation(row.id)
      this.operation = false;
      this.dataForm = Object.assign({}, row)


    },
    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        //【API请求】----保存数据
        this.$api.saveSExam(this.dataForm).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
        }).catch((res) => {
              this.editLoading = false;//关闭loading框
              this.$notify({
                title: '保存失败',
                message: res,
                type: "error"
              });
            }
        )
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteSExam({ids: row.id,cerId:row.cerId}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({message: '操作失败', type: 'error'})
      });
    },
    //初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        examSubject: '',
        difficult: '',
        ifFree: 1,
        passScore: '',
        totalScore: '',
        questionCount: '',
        examCount: '',
        examCountPractice:'1000',
        examType: 1,
        orderNo: '',
        examStatus: '',
        practiceExamStrategy:'',
        examDuration: '',
        examForm: '',
        examLevel: '',
        examDesc: '',
        examIntro: '',
        examEndTime: '',
        signStartTime: '',
        ifPractice:'',
        signEndTime: '',
        suitGroup: '',
        examStartTime: '',
        id: '',
        examName: '',
        examImg: '',
        examImgMobile:'',
        certId: '',
        salePrice: '',
        originPrice: '',
        answerType:'',
      };
    },
    //关闭表单弹出框
    closeDialog() {
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },
    getSubjectList() {
      //【API请求】----获取表格列表数据
      this.$api.getSSubjectList({
        searchParam:{
          SEARCH_EQ_type:1,
        },
        orderParam: {
          order_no: true
        }
      }).then(response => {
        console.log(response)
        this.subjectList = response.data.content
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },
    getStrategyList() {
      //【API请求】----获取表格列表数据
      this.$api.getSExamPaperStrategyList().then(response => {
        this.strategyList = response.data.content
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },

    handleLot(row){
      this.examLogDialog = true
      this.pid = row.id
      this.examStartTime = row.examStartTime
      this.examEndTime = row.examEndTime
    },
    handleDiscount(row){
      this.pid=row.id
      this.showDiscount = true
    },

  }


}
</script>

